package com.eipv.multidatasource.component.pool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhuxiaolong
 * @description
 * @date 2019/3/21 16:38
 */
public class MigrateThreadPool {


    private ThreadPoolExecutor threadPool;

    private MigrateThreadPool() {
        //IO密集型任务，因此线程池设置线程数量多点便于增加吞吐量
        threadPool = new ThreadPoolExecutor(50, 100, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), new CustomThreadFactory(), new CustomRejectedExecutionHandler());
    }

    private class CustomThreadFactory implements ThreadFactory {

        private AtomicInteger count = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            String threadName = MigrateThreadPool.class.getSimpleName() + "-" + count.getAndAdd(1);
            t.setName(threadName);
            return t;
        }
    }

    private class CustomRejectedExecutionHandler implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            //任务提交多于100个时的处理策略，此处处理方式为新增的任务交由提交线程来执行
            if (!executor.isShutdown()) {
                r.run();
            }
        }
    }


    private static class SingleInstanceHolder {
        private static MigrateThreadPool pool = new MigrateThreadPool();
    }


    public static ThreadPoolExecutor getThreadPool() {
        return SingleInstanceHolder.pool.threadPool;
    }
}
